package com.bd.rj.backstage.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.bd.rj.backstage.service.IUserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Resource
    IUserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public Map<String, Object> login(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password, HttpSession session) {
        Map<String, Object> login = userService.getLogin(username, password);
        Map<String, Object> map = new HashMap<>();
        //校验非空
        if (username!=null && !"".equals(username) && password!=null && !"".equals(password)) {
            session.setAttribute("login", login);
            if (login != null) {
                StpUtil.login(login.get("id"));
                login.put("satoken", StpUtil.getTokenInfo());
                map.put("code", 200);
                map.put("msg", "登录成功");
                map.put("data", login);
            } else {
                map.put("code", 201);
                map.put("msg", "登录失败");
                map.put("data", "error");
            }
        }
        //更新用户在线信息
        return map;
    }

    /**
     * @desc 检测登陆状态调试接口
     * @author 白世俊
     * @date 2025/1/4
     */
    @SaCheckLogin
    @RequestMapping(value = "/checklogin", method = RequestMethod.GET)
    public Map<String, Object> checkLogin() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "登录状态正常");
        map.put("data", StpUtil.getTokenInfo());
        return map;
    }

    /**
     * @desc 供调试获取登录用户id
     * @author 白世俊
     * @date 2025/1/4
     */
    @RequestMapping(value = "/checkuserrole", method = RequestMethod.GET)
    public Map<String, Object> checkRole() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "角色id获取成功");
        map.put("data", StpUtil.getRoleList().get(0));
        return map;
    }
    /**
     * @desc 退出登录
     * @author 白世俊
     * @date 2025/1/5
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Map<String, Object> logout() {
        StpUtil.logout();
         Map<String, Object> map = new HashMap<>();
                 map.put("code", 200);
                 map.put("msg", "退出登录成功");
                 map.put("data", new Date());
                return map;
    }
}
